/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 1.c
> Author:cjy
> Mail: 
> Created Time: 2024年08月07日 星期三 11时22分16秒
***************************************************/
//将指定目录下的两个文件用两个线程同时拷贝到目标位置。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
void copyFile(char *src, char *dst);
void copyFile(char *src, char *dst) {
    int fd = 0, fb = 0;
    char buffer[1024];
    ssize_t ret = 0;

    // 打开源文件
    fd = open(src, O_RDONLY);
    if (fd == -1) {
        perror("open source file");
        exit(-1);
    }

    // 打开目标文件
    fb = open(dst, O_RDWR | O_CREAT | O_TRUNC, 0640);
    if (fb == -1) {
        perror("open destination file");
        close(fd);
	exit(-1);
    }

    // 读取和写入数据
    while ((ret = read(fd, buffer, sizeof(buffer))) > 0) {
        if (write(fb, buffer, ret) != ret) {
            perror("write");
            close(fd);
            close(fb);
	    exit(-1);
        }
    }

    if (ret == -1) {
        perror("read");
    } else if (ret == 0) {
        // 文件读取完成
	printf("ok");
    }

    // 关闭文件描述符
    close(fd);
    close(fb);
}

void *fun1(void *arg){
		printf("nihao:%ld\n",pthread_self());
	        char src[] = "./1.txt";
    		char dst[] = "./2.txt";
		copyFile(src,dst);
}

void *fun2(void *arg){
		printf("cjy:%ld\n",pthread_self());
		char src[] = "./1.txt";
    		char dst[] = "./3.txt";
		copyFile(src,dst);
	
}
int main(int argc,const char* argv[])
{
	int ret = 0;
	pthread_t id1 = 0;
	pthread_t id2 = 0;
	pthread_t id3 = pthread_self();
	ret = pthread_create(&id1,NULL,fun1,NULL);
	if(ret != 0){
		perror("pthread_create");
		exit(-1);
	}
	ret = pthread_create(&id2,NULL,fun2,NULL);
	if(ret != 0){
		perror("pthread_create");
		exit(-1);
	}
	for(int i = 0;i < 5;i++){
		printf("%dmain_id is %ld\n",i,id3);
		sleep(1);
	}
	
	pthread_join(id1,NULL);
	pthread_join(id2,NULL);
    return 0;
}
